include make/previous.mk
OUTPUT_DIR := output
# 确保OUTPUT_DIR存在
$(shell mkdir -p $(OUTPUT_DIR))

INCLUDE_DIR += include

CXXFLAGS = -std=c++14 -Wall -I$(INCLUDE_DIR)
CXXLDLIBS = -lncurses -pthread
# 查找所有子目录中的cpp文件和c文件
CXXSRCS = $(shell find . -name '*.cpp' -exec grep -l 'int main' {} \;)
CXXBINS := $(patsubst ./%, $(OUTPUT_DIR)/%, $(CXXSRCS:.cpp=.out))

CFLAGS = -Wall -I$(INCLUDE_DIR) 
CCLDLIBS = -lncurses
CCSRCS = $(shell find . -name '*.c' -exec grep -l 'int main' {} \;)
CCBINS := $(patsubst ./%, $(OUTPUT_DIR)/%, $(CCSRCS:.c=.out))

PY = python3
PYSRCS = $(shell find . -name '*.py')
PYBINS := $(patsubst ./%, $(OUTPUT_DIR)/%, $(PYSRCS:.py=.py))


all: $(CXXBINS) $(CCBINS) $(PYBINS) execute todo

todo:
	@cat note.txt

# 创建必要的目录并编译C++文件
$(OUTPUT_DIR)/%.out: %.cpp
	@mkdir -p $(dir $@)
	@echo "\033[0;32mCXX\033[0m $<"
	@$(CXX) $(CXXFLAGS) $< -o $@ $(CXXLDLIBS)

# 创建必要的目录并编译C文件
$(OUTPUT_DIR)/%.out: %.c
	@mkdir -p $(dir $@)
	@echo "\033[0;32mCC\033[0m $<"
	@$(CC) $(CFLAGS) $< -o $@ $(CCLDLIBS)

# 对Python文件不做处理，只输出跳过信息
$(OUTPUT_DIR)/%.py: %.py
	@mkdir -p $(dir $@)
	@echo "\033[0;32mPY\033[0m skip $<"

# 通用编译和执行目标
run: todo
ifndef SRC
	$(error SRC variable is not set)
endif
	@echo "\033[0;32m\n[$(SRC)] Executing ...\n----------------------------------------------------------------\033[0m"
	@$(if $(filter %.cpp,$(SRC)), \
		$(CXX) $(CXXFLAGS) $(SRC) -o $(OUTPUT_DIR)/$(notdir $(basename $(SRC))).out $(CXXLDLIBS) && $(OUTPUT_DIR)/$(notdir $(basename $(SRC))).out | sed 's/^/|    /', \
		$(if $(filter %.c,$(SRC)), \
			$(CC) $(CFLAGS) $(SRC) -o $(OUTPUT_DIR)/$(notdir $(basename $(SRC))).out $(CCLDLIBS) && $(OUTPUT_DIR)/$(notdir $(basename $(SRC))).out | sed 's/^/|    /', \
			$(if $(filter %.py,$(SRC)), \
				$(PY) $(SRC) | sed 's/^/|    /', \
				$(error Unsupported file type for SRC: $(SRC)) \
			) \
		) \
	)
	@echo "\033[0;32m----------------------------------------------------------------\033[0m";

execute: todo
	@echo "拿下LeetCode!"
	@for bin in $(CXXBINS); do \
		echo "\033[0;32m\n[$$bin.cpp] Executing ...\n----------------------------------------------------------------\033[0m"; \
		./$$bin | sed 's/^/|    /'; \
		echo "\033[0;32m----------------------------------------------------------------\033[0m"; \
	done
	@for bin in $(CCBINS); do \
		echo "\033[0;32m\n[$$bin.c] Executing ...\n----------------------------------------------------------------\033[0m"; \
		./$$bin | sed 's/^/|    /'; \
		echo "\033[0;32m----------------------------------------------------------------\033[0m"; \
	done
	@for bin in $(PYSRCS); do \
		echo "\033[0;32m\n[$$bin] Executing ...\n----------------------------------------------------------------\033[0m"; \
		$(PY) ./$$bin | sed 's/^/|    /'; \
		echo "\033[0;32m----------------------------------------------------------------\033[0m"; \
	done

clean:
	@rm -f $(CXXBINS) $(CCBINS) *.out *.o *.pyc
	@rm -rf output

include make/after.mk

